package com.ruoyi.service;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.KongAdmin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@Service("Consumer")
public class Consumer {
    @Autowired
    KongAdmin kongAdmin;
    private String PrivateKey="asdew";

    public static String encryptString(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(input.getBytes());
            byte[] digest = md.digest();
            StringBuilder sb = new StringBuilder();
            for (byte b : digest) {
                sb.append(String.format("%02x", b & 0xff));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return input;
        }
    }
    public String getConsumer(String commerceName )
    {
        if(commerceName==null){
            return null;
        }else {
        String name=commerceName;
        JSONObject requestBody = new JSONObject();
        requestBody.put("username", name);
            String info=  kongAdmin.CreateConsumer(requestBody);
            System.out.println(info);
        return name;}
    }

    public String createAPIKey(String cname)
    {
        JSONObject requestBody = new JSONObject();
        String key=encryptString(cname+PrivateKey);
        requestBody.put("key", key);
       // requestBody.put("name", cname+"key");
        String info=  kongAdmin.CreatePluginInConsumer(requestBody,cname,"key-auth");
        System.out.println(info);
        return key;
    }
    public String APIKey(String cname)
    {
        JSONObject requestBody = new JSONObject();
        String key=encryptString(cname+PrivateKey);
        requestBody.put("key", key);
        // requestBody.put("name", cname+"key");
        String info=  kongAdmin.CreatePluginInConsumer(requestBody,cname,"key-auth");
        System.out.println(info);
        return info;
    }

    public String DelUser(String uname)
    {
        String info=  kongAdmin.DeleteConsumer(uname);
        System.out.println(info);
        return info;
    }

    public String  delAPIKey(String rep,String cname)
    {
        JSONObject requestBody = JSONObject.parseObject(rep);
        JSONArray data=requestBody.getJSONArray("data");
         JSONObject infor=data.getJSONObject(0);
        String id=  infor.getString("id");
      String k=  kongAdmin.DeletePluginInConsumer(cname, "key-auth",id);
      System.err.println(k);
      return "ok";
    }

    public String getit(String url)
    {
        return kongAdmin.getIt(url);
    }
}
